import React, {useState, useEffect} from 'react';
import {Editor} from "react-draft-wysiwyg";
import {convertToRaw, ContentState, EditorState} from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

import './NewsEditor.css';

export default function NewsEditor(props) {

    const [editorState, setEditorState] = useState('')

    useEffect(() => {
        // html ==> draft
        if (props.content === undefined) {
            return
        }
        const html = props.content;
        const contentBlock = htmlToDraft(html);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const editorState = EditorState.createWithContent(contentState);
            setEditorState(editorState)
        }
    }, [props.content])

    return (
        <div>
            <Editor
                localization={{locale: 'zh'}}   // 设置为中文

                editorState={editorState}
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName="editorClassName"
                onEditorStateChange={(editorState) => setEditorState(editorState)}   // editorState 与 onEditorStateChange 要一起搭配使用，使该组件成为受控组件；onEditorStateChange每次状态更新都会重新刷新

                // 失去焦点触发事件
                onBlur={() => {
                    // console.log(draftToHtml(convertToRaw(editorState.getCurrentContent())))
                    // 回传给父组件
                    props.getEditorContent(draftToHtml(convertToRaw(editorState.getCurrentContent())))
                }}
            />
        </div>
    )
}